package org.chen.flight.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.chen.common.task.ScheduledTaskEntity;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务Mapper
 */
@Mapper
public interface ScheduledTaskMapper extends BaseMapper<ScheduledTaskEntity> {
    
    /**
     * 根据状态查询任务
     */
    @Select("SELECT * FROM flight_scheduled_flight_task WHERE status = #{status} ORDER BY created_at DESC")
    List<ScheduledTaskEntity> findByStatus(@Param("status") String status);
    
    /**
     * 查询活跃的任务（用于系统启动时恢复）
     */
    @Select("SELECT * FROM flight_scheduled_flight_task WHERE status IN ('ACTIVE', 'PAUSED') ORDER BY created_at DESC")
    List<ScheduledTaskEntity> findActiveTasks();
    
    /**
     * 更新任务执行统计
     */
    @Update("UPDATE flight_scheduled_flight_task SET " +
            "total_run_count = #{totalRunCount}, " +
            "success_count = #{successCount}, " +
            "failed_count = #{failedCount}, " +
            "last_run_at = #{lastRunAt}, " +
            "last_run_result = #{lastRunResult}, " +
            "last_error_message = #{lastErrorMessage}, " +
            "last_execution_summary = #{lastExecutionSummary}, " +
            "updated_at = NOW() " +
            "WHERE id = #{id}")
    int updateExecutionStats(@Param("id") String id,
                           @Param("totalRunCount") Integer totalRunCount,
                           @Param("successCount") Integer successCount,
                           @Param("failedCount") Integer failedCount,
                           @Param("lastRunAt") LocalDateTime lastRunAt,
                           @Param("lastRunResult") String lastRunResult,
                           @Param("lastErrorMessage") String lastErrorMessage,
                           @Param("lastExecutionSummary") String lastExecutionSummary);
    
    /**
     * 更新任务状态
     */
    @Update("UPDATE flight_scheduled_flight_task SET status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") String id, @Param("status") String status);
    
    /**
     * 批量更新状态（用于系统关闭时）
     */
    @Update("UPDATE flight_scheduled_flight_task SET status = 'STOPPED', updated_at = NOW() WHERE status = 'ACTIVE'")
    int stopAllActiveTasks();
}